import config from '@/config'
import { onMounted, onUnmounted, provide, ref, watch } from 'vue'
import {
  dicItemByCode,
  getProductionLineMode,
  getTHProcessHistoryData,
  getTHProcessRealtimeData,
  getTHTabulateData, sameDayProductionLineCode
} from '@/api/mesApi'
import { useI18n } from 'vue-i18n'

let task = null

const killTask = () => {
  if (task) {
    clearInterval(task)
  }
}
const today = new Date();

// 获取当前月份的第一天
const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

// 获取当前月份的最后一天
const lastDayOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
const createData = async (remoteData, queryParams) => {
  const {
    productionLineCode,
    shiftCode,
    mesProduceDate,
    mesProduceDate1
  } = queryParams
  if (!productionLineCode) {
    return
  }
  /* 1.获取历史数据 */
  await getTHProcessHistoryData({
    productionLineCode: queryParams.productionLineCode,
    shiftCode: queryParams.shiftCode ? queryParams.shiftCode : 'ALL',
    mesProduceDate: queryParams.mesProduceDate ? queryParams.mesProduceDate : firstDayOfMonth.toISOString().split('T')[0],
    mesProduceDate1: queryParams.mesProduceDate1 ? queryParams.mesProduceDate1 : lastDayOfMonth.toISOString().split('T')[0],
    processCode: 'TH',
    current: queryParams.page,
    size: queryParams.rows
  }).then(function (res) {
    if (res.code === 0) {
      remoteData.value.historyData = [...res.data.records]
    } else {
      remoteData.value.historyData = []
    }
    queryParams.total = res.data.total
  }, function () {
    remoteData.value.historyData = []
  })
  /* 2、获取汇总数据 */
  await getTHTabulateData({
    shiftCode,
    mesProduceDate,
    mesProduceDate1
  }).then(function (res) {
    if (res) {
      for (const item of remoteData.value.processCount) {
        item.value = res.data?.[item.field] || 0
      }
    }
  }, function (e) {
    console.error(e)
  })
  /* 3.获取单条线汇总数据 */
  await getTHTabulateData({
    productionLineCode,
    shiftCode: queryParams.shiftCode ? queryParams.shiftCode : 'ALL',
    processCode: 'TH',
    mesProduceDate,
    mesProduceDate1
  }).then(async function (res) {
    // if (res) {
    // console.log(res)
    const value = remoteData.value.processCount[0].value || 0
    const value1 = remoteData.value.processCount[1].value || 0
    const value2 = remoteData.value.processCount[2].value || 0
    const value3 = remoteData.value.processCount[3].value || 0
    const value4 = remoteData.value.processCount[4].value || 0
    const value5 = remoteData.value.processCount[5].value || 0
    const ProduceQtyPer = (value ? (res.data.produceQty || 0) / value : 0).toFixed(3)
    const PvcInputQtyPer = (value1 ? (res.data.pvcInputQty || 0) / value1 : 0).toFixed(3)
    const LvtInputQtyPer = (value2 ? (res.data.lvtInputQty || 0) / value2 : 0).toFixed(3)
    const GlueInputQtyPer = (value3 ? (res.data.glueInputQty || 0) / value3 : 0).toFixed(3)
    const LVTStandardDeductionQTYPer = (value4 ? (res.data.lvtStandardDeductionQTY || 0) / value4 : 0).toFixed(3)
    const PVCStandardDeductionQTYPer = (value5 ? (res.data.pvcStandardDeductionQTY || 0) / value5 : 0).toFixed(3)
    // 总产出片数 总产出托数 总标准扣料量 总投料量
    remoteData.value.lineCount = {
      ProduceQty: res.data.produceQty || 0,
      PvcInputQty: res.data.pvcInputQty || 0,
      LvtInputQty: res.data.lvtInputQty || 0,
      GlueInputQty: res.data.glueInputQty || 0,
      LVTStandardDeductionQTY: res.data.lvtStandardDeductionQTY || 0,
      PVCStandardDeductionQTY: res.data.pvcStandardDeductionQTY || 0,
      ProduceQtyPer,
      PvcInputQtyPer,
      LvtInputQtyPer,
      GlueInputQtyPer,
      LVTStandardDeductionQTYPer,
      PVCStandardDeductionQTYPer
    }
    // }
  }, function (e) {
    console.error(e)
  })
  /* 4.获取获取实时数据 */
  let realTimeData = null
  await getTHProcessRealtimeData({ productionLineCode }).then(function (res) {
    realTimeData = res.data
  })
  /* 5.查询产线当前模式 */
  await getProductionLineMode({ productionLineCode }).then(function (res) {
    let obj = res.data
    if (obj!==null&&obj!==undefined&&realTimeData!==null&&realTimeData!==undefined) {
      Object.assign(realTimeData, obj)
    }
  }, function (e) {
    console.error(e)
  })
  remoteData.value.realTimeData = { ...realTimeData }
  /* 6.查询工序当天正在生产的产线 */
  sameDayProductionLineCode({ processCode: 'TH' }).then(function (res) {
    remoteData.value.currentProductionLine = res.data
  })
  /* 7.数据字典获取JC条线自动刷新的频率 */
  dicItemByCode({ code: 'THVIEW' }).then(function (res) {
    remoteData.value.refreshFrequency = res.data
  })
}
const dataReady = (remoteData, once, queryParams) => {
  createData(remoteData, queryParams)
  remoteData.value.ready = true
  if (!once && !task) {
    task = setInterval(async () => {
      await createData(remoteData, queryParams)
    }, 100000)
  }
}

export default function getTHData(queryParams, once) {
  // 获取班次日期相关信息
  const { t } = useI18n()

  const remoteData = ref({
    ready: false,
    historyData: [],
    realTimeData: {},
    lineCount: {},
    refreshFrequency: [], // 刷新频率
    currentProductionLine: [], // 当前生产工序产线
    processCount: [
      {
        name: t('wms.thTotlaOutput'),
        field: 'ProduceQty',
        icon: config.ossUrl + '/afl-data-screen/images/icon-all-input.png',
        value: 0,
        span: 4,
        unit: 'pcs'
      },
      {
        name: t('wms.pvcTotalInput'),
        field: 'PvcInputQty',
        icon: config.ossUrl + '/afl-data-screen/images/icon-output.png',
        value: 0,
        span: 4,
        unit: 'pcs'
      },
      {
        name: t('wms.lvtTotalInput'),
        field: 'LvtInputQty',
        icon: config.ossUrl + '/afl-data-screen/images/icon-input.png',
        value: 0,
        span: 4,
        unit: 'pcs'
      },
      {
        name: t('wms.totalAdhesive'),
        field: 'GlueInputQty',
        icon: config.ossUrl + '/afl-data-screen/images/icon-takeOut.png',
        value: 0,
        span: 4,
        unit: 'kg'
      },
      {
        name: t('wms.lvtMaterials'),
        field: 'LVTStandardDeductionQTY',
        icon: config.ossUrl + '/afl-data-screen/images/icon-search.png',
        value: 0,
        span: 4,
        unit: 'pcs'
      },
      {
        name: t('wms.pvcBuckle'),
        field: 'PVCStandardDeductionQTY',
        icon: config.ossUrl + '/afl-data-screen/images/icon-sys.png',
        value: 0,
        span: 4,
        unit: 'pcs'
      }
    ]
  })
  /* 挂在操作 */
  onMounted(() => dataReady(remoteData, once, queryParams))
  onUnmounted(killTask)
  /* 监听操作 */
  watch(() => queryParams, () => {
    remoteData.value.realTimeData = {}
    dataReady(remoteData, true, queryParams)
  }, { deep: true })
  return { remoteData }
}
